﻿using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Security;
using WebApp.Services;
using Models.Models;
using System;
using System.Configuration;
using WebApp.Classes;
using Models.Responses;

namespace WebApp.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            return View(new Login() { ReturnUrl = returnUrl });
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(Login model)
        {
            if (ModelState.IsValid)
            {
                var response = new AccountService().ValidateUser(model);
               
                model.SecureQuestion = response.User.SecureQuestion;

                if (response.User.UserID > 0)
                {
                    FormsAuthentication.SetAuthCookie(model.UserEmail, model.RememberMe);

                    var userMenu = new AccountService().GetMenuOptions(new User() { UserID = (long)response.User.UserID });

                    userMenu.UserPermissions.User.SecureQuestion = userMenu.UserPermissions.User.SecureQuestion;

                    new UserCookie().Set(userMenu.UserPermissions.User);

                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return Redirect(model.ReturnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, response.ErrorMessage);
                }
            }

            return View(model);
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult RetrievePassword(PasswordReminder model)
        {
            var response = new AccountService().ValidateSecureAnswer(model);
            var result = string.Empty;

            if (response.IsSuccessful)
            {
                result = Statics.GetSuccessWindow(String.Format("Password was sent to {0}", model.UserEmail));
            }
            else
            {
                result = Statics.GetWarningWindow(response.ErrorMessage);
            }

            return JavaScript(result);
        }

        public ActionResult ChangePassword()
        {
            var cookie = new UserCookie().Get().User;

            return View(new ChangePassword { UserID = (long)cookie.UserID });
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePassword model)
        {
            string result = string.Empty;

            if (ModelState.IsValid)
            {
                var response = new AccountService().ChangePassword(model);

                if (response.IsSuccessful)
                {
                    result = Statics.GetSuccessWindow("Password was changed");
                }
                else
                {
                    result = Statics.GetWarningWindow(response.ErrorMessage);
                }
            }

            return JavaScript(result);
        }

        public ActionResult UserManagement(int pageIndex = 1, string sortColumn = "UserID", string sortDirection = "DESC", bool hideRevoked = false)
        {
            var user = new UserCookie().Get().User;
            var list = new AccountService().GetUserListByStore(user, pageIndex, Convert.ToInt32(ConfigurationManager.AppSettings.Get("PageSize")), sortColumn, sortDirection, hideRevoked);

            ViewBag.hideRevoked = hideRevoked;

            return View(new UserList() { List = list.UserList.List, PageIndex = list.UserList.PageIndex, PageSize = list.UserList.PageSize, SortColumn = list.UserList.SortColumn, SortDirection = list.UserList.SortDirection, ResultCount = list.UserList.ResultCount });
        }

        public ActionResult UserProfile()
        {
            var cookie = new UserCookie().Get().User;
            var user = new AccountService().GetMenuOptions(cookie).UserPermissions.User;

            return View(user);
        }

        [HttpPost]
        public ActionResult UserProfile(User model)
        {
            if (ModelState.IsValid)
            {
                model.UserUpdated = model.UserID;

                var response = UpdateUser(model);

                if (response.IsSuccessful)
                {
                    new UserCookie().Set(model);

                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, response.ErrorMessage);
                }
            }

            return View();        
        }

        public PartialViewResult CreateUser()
        {
            var cookie = new UserCookie().Get().User;

            return PartialView("EditUserPartial", new UserPermissions() { User = new User() { UserID = 0, StoreID = cookie.StoreID } });
        }

        [HttpPost]
        public ActionResult CreateUser(User model)
        {
            if (ModelState.IsValid)
            {
                var cookie = new UserCookie().Get().User;
                model.UserUpdated = cookie.UserID;

                var response = new AccountService().CreateUser(model);

                if (response.ErrorNumber > 0)
                {
                    return JavaScript(Statics.GetWarningWindow(response.ErrorMessage));
                }
            }
            else
            {
                return JavaScript(Statics.GetWarningWindow("The form you're trying to submit containts validation errors!"));
            }

            return JavaScript(string.Format("window.location.href='{0}{1}'", this.HttpContext.Request.ApplicationPath, "/Account/UserManagement"));
        }

        public PartialViewResult EditViewUser(long? id)
        {
            var model = new UserPermissions();

            if (id != null && id > 0)
            {
                model = new AccountService().GetMenuOptions(new User() { UserID = id }).UserPermissions;
            }

            return PartialView("EditUserPartial", model);
        }

        [HttpPost]
        public ActionResult EditUser(UserPermissions model, FormCollection collection)
        {
            if (ModelState.IsValid)
            {
                var response = UpdateUser(model.User);

                if (response.ErrorNumber > 0)
                {
                    return JavaScript(Statics.GetWarningWindow(response.ErrorMessage));
                }

                response = UpdatePermissions(collection);

                if (response.ErrorNumber > 0)
                {
                    return JavaScript(Statics.GetWarningWindow(response.ErrorMessage));
                }
            }
            else
            {
                return JavaScript(Statics.GetWarningWindow("The form you're trying to submit containts validation errors!"));
            }

            return JavaScript(string.Format("window.location.href='{0}{1}'", this.HttpContext.Request.ApplicationPath, "/Account/UserManagement"));
            //return new RedirectResult(string.Format("{0}{1}", this.HttpContext.Request.ApplicationPath, "/Account/UserManagement"));
        }

        public ActionResult ChangeStore(string path, int storeID)
        {
            var cookie = new UserCookie().Get().User;
            cookie.StoreID = storeID;
            new UserCookie().Set(cookie);

            var route = path.Split(new char[] { '/' });

            return RedirectToAction(route[1], route[0]);
        }

        public ActionResult ResetPassword(int userID)
        {
            string result = string.Empty;

            if (ModelState.IsValid)
            {
                var response = new AccountService().ChangePassword(new ChangePassword() { UserID = userID });

                if (response.IsSuccessful)
                {
                    result = Statics.GetSuccessWindow("Password was reset");
                }
                else
                {
                    result = Statics.GetWarningWindow(response.ErrorMessage);
                }
            }

            return JavaScript(result);
        }

        public ActionResult Revoke(long id)
        {
            string result = string.Empty;

            var cookie = new UserCookie().Get().User;                
            var response = new AccountService().ChangeUserStatus(new User() { UserID = id, UserUpdated = cookie.UserID, RevokeStatus = true });

            return new RedirectResult(string.Format("{0}{1}", this.HttpContext.Request.ApplicationPath, "/Account/UserManagement"));
        }

        public ActionResult Activate(long id)
        {
            string result = string.Empty;

            var cookie = new UserCookie().Get().User;
            var response = new AccountService().ChangeUserStatus(new User() { UserID = id, UserUpdated = cookie.UserID, RevokeStatus = false });

            return new RedirectResult(string.Format("{0}{1}", this.HttpContext.Request.ApplicationPath, "/Account/UserManagement"));
        }

        public ActionResult LogOff()
        {
            System.Web.HttpContext.Current.Response.Cookies.Clear();
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        private SuccessFailResponse UpdateUser(User user)
        {
            var cookie = new UserCookie().Get().User;
            user.UserUpdated = cookie.UserID;

            return new AccountService().UpdateUser(user);            
        }

        private SuccessFailResponse UpdatePermissions(FormCollection collection)
        {
            MenuItemList list = new MenuItemList() { List = new List<MenuItem>() };

            foreach (var value in collection)
            {
                if (value.ToString().StartsWith("status"))
                {
                    list.List.Add(new MenuItem()
                    {
                        ID = Convert.ToInt32(value.ToString().Replace("status", string.Empty)),
                        Status = Convert.ToInt32(collection[value.ToString()])
                    });
                }
            }

            var user = new UserCookie().Get().User;

            return new AccountService().UpdateMenuOptions(user, list);
        }
    }
}
